package com.qiezikaka.kaka.http;

import android.os.Handler;
import android.os.Looper;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.HttpUrl;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class HttpClient {

    private static final OkHttpClient client;
    private static final Handler handler = new Handler(Looper.getMainLooper());
    private static final Gson gson = new Gson();

    static {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .addInterceptor(logging)
                .build();
    }

    public static <T> void get(String url, Map<String, String> params, Class<T> responseType, HttpResponseCallback<T> callback) {
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            urlBuilder.addQueryParameter(param.getKey(), param.getValue());
        }

        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .get()
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> callback.onFailure(e.getMessage()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseBody = response.body().string();
                        T data = gson.fromJson(responseBody, responseType);
                        handler.post(() -> callback.onSuccess(data));
                    } catch (JsonSyntaxException e) {
                        handler.post(() -> callback.onFailure("JSON解析错误: " + e.getMessage()));
                    }
                } else {
                    handler.post(() -> callback.onFailure(response.message()));
                }
            }
        });
    }

    public static <T> void post(String url, Map<String, String> params, Class<T> responseType, HttpResponseCallback<T> callback) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        String json = gson.toJson(params);
        RequestBody body = RequestBody.create(json, mediaType);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> callback.onFailure(e.getMessage()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseBody = response.body().string();
                        T data = gson.fromJson(responseBody, responseType);
                        handler.post(() -> callback.onSuccess(data));
                    } catch (JsonSyntaxException e) {
                        handler.post(() -> callback.onFailure("JSON解析错误: " + e.getMessage()));
                    }
                } else {
                    handler.post(() -> callback.onFailure(response.message()));
                }
            }
        });
    }

    public static <T> void post(String url, Map<String, String> params, File file, String fileType, Class<T> responseType, HttpResponseCallback<T> callback) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);

        // 添加表单参数
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
        }

        // 添加文件部分
        if (file != null) {
            // 文件读取检查
            byte[] fileBytes = null;
            try {
//                fileBytes = Files.readAllBytes(file.toPath());
                fileBytes = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
            } catch (IOException e) {
                handler.post(() -> callback.onFailure("文件读取错误: " + e.getMessage()));
                return;
            }

            String fileName = file.getName();
//            RequestBody fileBody = RequestBody.create(MediaType.parse(fileType), file);
            RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), fileBytes);
            builder.addFormDataPart("file", fileName, fileBody);
        }

        RequestBody requestBody = builder.build();

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> callback.onFailure(e.getMessage()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseBody = response.body().string();
                        T data = gson.fromJson(responseBody, responseType);
                        handler.post(() -> callback.onSuccess(data));
                    } catch (JsonSyntaxException e) {
                        handler.post(() -> callback.onFailure("JSON解析错误: " + e.getMessage()));
                    }
                } else {
                    handler.post(() -> callback.onFailure(response.message()));
                }
            }
        });
    }

    public static <T> void postTest(String url, Map<String, String> params, File file, String fileType, Class<T> responseType, HttpResponseCallback<T> callback) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);

        // 添加表单参数
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
        }

        // 添加文件部分
        if (file != null) {
            // 文件读取检查
            byte[] fileBytes = null;
            try {
//                fileBytes = Files.readAllBytes(file.toPath());
                fileBytes = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
            } catch (IOException e) {
                handler.post(() -> callback.onFailure("文件读取错误: " + e.getMessage()));
                return;
            }

            String fileName = file.getName();
//            RequestBody fileBody = RequestBody.create(MediaType.parse(fileType), file);
            RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), fileBytes);
            builder.addFormDataPart("file", fileName, fileBody);
        }

        RequestBody requestBody = builder.build();

        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> callback.onFailure(e.getMessage()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseBody = response.body().string();
                        T data = gson.fromJson(responseBody, responseType);
                        handler.post(() -> callback.onSuccess(data));
                    } catch (JsonSyntaxException e) {
                        handler.post(() -> callback.onFailure("JSON解析错误: " + e.getMessage()));
                    }
                } else {
                    handler.post(() -> callback.onFailure(response.message()));
                }
            }
        });
    }

    public static <T> void post01(String url, Map<String, String> params, File file, String fileType, Class<T> responseType, HttpResponseCallback<T> callback) {
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        // 添加表单参数
        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.addFormDataPart(entry.getKey(), entry.getValue());
        }

        // 添加文件部分
        if (file != null) {
            // 文件读取检查
            byte[] fileBytes = null;
            try {
//                fileBytes = Files.readAllBytes(file.toPath());
                fileBytes = Files.readAllBytes(Paths.get(file.getAbsolutePath()));
            } catch (IOException e) {
                handler.post(() -> callback.onFailure("文件读取错误: " + e.getMessage()));
                return;
            }

            String fileName = file.getName();
//            RequestBody fileBody = RequestBody.create(MediaType.parse(fileType), file);
            RequestBody fileBody = RequestBody.create(MediaType.parse("image/jpeg"), fileBytes);
            builder.addFormDataPart("photo", fileName, fileBody);
        }

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.post(() -> callback.onFailure(e.getMessage()));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    try {
                        String responseBody = response.body().string();
                        T data = gson.fromJson(responseBody, responseType);
                        handler.post(() -> callback.onSuccess(data));
                    } catch (JsonSyntaxException e) {
                        handler.post(() -> callback.onFailure("JSON解析错误: " + e.getMessage()));
                    }
                } else {
                    handler.post(() -> callback.onFailure(response.message()));
                }
            }
        });
    }



    public interface HttpResponseCallback<T> {
        void onSuccess(T data);
        void onFailure(String error);
    }
}